<?php
namespace control;
//管理员后台-移库记录
use JetBrains\PhpStorm\NoReturn;

class moveStockRecordClass extends adIndexClass
{
	private const title       = '移库记录';
	private const page        = 'moveStockRecord';
	private const table       = 'inventory_transfer';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'typeName'          => [
                        'name'  => '{l.moveStockRecord.home.typeId}',
                        'width' => 150,
                    ],
                    'code' => [
                        'name'  => '{l.moveStockRecord.home.code}',
                        'width' => 150,
                    ],
                    'name'  => [
                        'name'  => '{l.moveStockRecord.home.name}',
                        'width' => 200,
                    ],
                    'model'  => [
                        'name'  => '{l.moveStockRecord.home.model}',
                        'width' => 150,
                    ],
                    'unit'  => [
                        'name'  => '{l.moveStockRecord.home.unit}',
                        'width' => 50,
                    ],
                    'batch'         => [
                        'name'  => '{l.moveStockRecord.home.batch}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'num'          => [
                        'name'  => '{l.moveStockRecord.home.num}',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'warehouseId'          => [
                        'name'  => '{l.moveStockRecord.home.outWarehouseId}',
                        'width' => 150,
                    ],
                    'positionId'          => [
                        'name'  => '{l.moveStockRecord.home.outLocation}',
                        'width' => 150,
                    ],
                    'inWarehouseId'          => [
                        'name'  => '{l.moveStockRecord.home.inWarehouseId}',
                        'width' => 150,
                    ],
                    'inLocationId'          => [
                        'name'  => '{l.moveStockRecord.home.inLocation}',
                        'width' => 150,
                    ],
                    'stid'          => [
                        'name'  => '{l.moveStockRecord.home.operator}',
                        'width' => 100,
                    ],
                    'time'          => [
                        'name'  => '{l.moveStockRecord.home.time}',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "产品分类" => materialClass::typeSelect(name: 'typeId'),
                    L('moveStockRecord.home.code')   => text(array("name" => "code")),
                    L('moveStockRecord.home.batch') => text(array("name" => "batch")),
                ],
                [
                    L('moveStockRecord.home.outWarehouseId') => selectMultiple(['table' => 'warehouse', 'where' => " coid = '" . self::$coid . "' AND state = '启用' ", 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'outWarehouseId', 'class' => 'width200']),
                    L('moveStockRecord.home.outLocation')   => text(["name" => "outLocation"]),
                    L('moveStockRecord.home.inWarehouseId') => selectMultiple(['table' => 'warehouse', 'where' => " coid = '" . self::$coid . "' AND state = '启用' ", 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'inWarehouseId', 'class' => 'width200',]),
                ],
                [
                    L('moveStockRecord.home.inLocation')  => text(["name" => "inLocation"]),
                    L('moveStockRecord.home.operator') => text(["name" => "operator"]),
                    L('moveStockRecord.home.time') => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date']])
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 查询表单
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData' class='spanButton'>".L('moveStockRecord.home.export')."</a>\n";
        }
		//返回
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*列表页-查询结果*/
	public function homeSearch($workFlow = null): bool|string
	{
		$where = " 1=1 and coid = '".self::$coid."' ";
        // 物料条件
        $mwhere = search([
            "="    => [
                'code' => $this->post('code'),
                'name' => $this->post('name'),
            ],
            "like" => [
                'typePath' => $this->post('typeId'),
            ],
        ]);
        if ($mwhere) {
            $where .= " AND materialId in (SELECT id FROM material WHERE 1=1 {$mwhere}  )  ";
        }
		$equal = [
			'warehouseId' => $this->post('outWarehouseId'),
			'inWarehouseId' => $this->post('inWarehouseId'),
			'isRevoke' => 0,
		];
		$like  = [
			'batch' => $this->post('batch'),
		];
        if ($this->post('outLocation')) {
            $where .= " AND positionId in (select id from warehouse_position where name like '%".$this->post('outLocation')."%') ";
        }
        if ($this->post('inLocation')) {
            $where .= " AND inLocationId in (select id from warehouse_position where name like '%".$this->post('inLocation')."%') ";
        }
        if ($this->post('orderDate')) {
            $where .= self::timeComparison($this->post('orderDate'), 'date', 'time');
        }
		//生成查询语句
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page  = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
		$_SESSION[self::page]['sql'] = $page['sql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate  = [
				"box" => [
					"name" => "listId", "value" => $array['id'],
				],
			];
            $material     = query('material', " id = '$array[materialId]'");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case 'warehouseId':
                    case 'inWarehouseId':
                        $row[] = warehouseClass::getName($array[$key]);
                        break;
                    case 'positionId':
                    case 'inLocationId':
                        $row[] = warehousePositionClass::getName($array[$key]);
                        break;
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case 'typeName':
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'];
		return json_encode($json, 320);
	}


	/**
	 * 导出
	 */
	#[NoReturn] public function exportData()
	{
		if (!$this->power(self::page, 'export')) {
			$_SESSION['warn'] = L('moveStockRecord.exportData.power');
		} else {
			$title = [L('moveStockRecord.home.typeId'), L('moveStockRecord.home.code'), L('moveStockRecord.home.name'), L('moveStockRecord.home.model'), L('moveStockRecord.home.unit'), L('moveStockRecord.home.batch'), L('moveStockRecord.home.num'), L('moveStockRecord.home.outWarehouseId'), L('moveStockRecord.home.outLocation'), L('moveStockRecord.home.inWarehouseId'), L('moveStockRecord.home.inLocation'), L('moveStockRecord.home.operator'), L('moveStockRecord.home.time')];
			$sql    = $_SESSION[self::page]['sql'];
			$result = self::sqlFind($sql);
			$data   = [];
			foreach ($result as $array) {
                $material     = query('material', " id = '$array[materialId]'");
                //本行
                $data[] = [
                    $material['typeName'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
                    $array['batch'],
                    self::lostZero($array['num'],'numPrecision'),
                    warehouseClass::getName($array['warehouseId']),
                    warehousePositionClass::getName($array['positionId']),
                    warehouseClass::getName($array['inWarehouseId']),
                    warehousePositionClass::getName($array['inLocationId']),
                    self::findStaff($array['stid']),
                    $array['time']
                ];
			}
			$text = str_replace(['{{staffName}}'], [$this->control['name']], lang('moveStockRecord.exportData.log'));
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, lang('moveStockRecord.exportData.fileName').".xlsx");
		}
		header("Location:" . getenv("HTTP_REFERER"));
		exit(0);
	}

}
